var app = getApp(),
  a = app.requirejs("core"),
  b = app.requirejs("api/kjb");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    popup:false,
    countDownDay: 0,
    countDownHour: 0,
    countDownMinute: 0,
    countDownSecond: 0,
    show_time: true,
    display: false,
    // pickerOption: {},
    // specsData: [],
    // specsTitle: "",
    // tempname: "",//弹框
    // showPicker: false,//页面阴暗效果
    // total: 1,   //默认选择数量
    // optionid: 0,//初始规格未选中的状态。buyNow()调用
    // spec_Show: true,
    active:''
  },

  onGotUserInfo: function (q) {
    var that = this,
        cache = app.getCache("userinfo");

    // if (cache) {
    //     return;
    // }
    app.getUserInfo(q.detail.userInfo, function (t) {
      if (t != 1000) {
        var ucache = getApp().getCache("userinfo");
        if (ucache) {
          //var options = that.data.options;
          //that.getDetail(options)
          //getCurrentPages()[getCurrentPages().length - 1].onLoad();
          that.setData({
            display: false,
            //getPhoneAuth: getApp().globalData.getphone
          })
        }
      } else {
        that.setData({
          display: true
        })
      }

    }, q.detail.encryptedData, q.detail.iv);
  },

  // 授权获取用户信息判断
  authCheck: function () {
    var cache = getApp().getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      this.setData({
        display: true
      })
      return false;
    } else {
      this.setData({
        display: false
      })
      return true;
    }
  },

  // 取消登录
  cancel_auth: function () {
    this.setData({
      display: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    a.setting();
    var that=this,
    status=false,

    id=options.id;
    if (options.form_id){
      var form_id = options.form_id;
    }
    if (options && options.card_id) {
      app.globalData.card_id = options.card_id;
    }
    that.setData(options);
    if (options.kj_stu && options.kj_stu==1){
      status=true
    }

    var cache = app.getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      getApp().authSwitch(function(res){
        if (res == 1) {
          that.setData({
            display: true
          })
        } else {
          that.setData({
            display: false
          })
        }
      })
    }

  b.BargainCreate(id,function(t){
    that.setData(t);
    that.detail();
    if (form_id && t.code==0){
    that.push(id, form_id);
    }
  },status)
  },
  
  detail:function(){
    var that=this,
      uid = getApp().getCache("userinfo").uid != undefined ? getApp().getCache("userinfo").uid : 0,
    id=that.data.id;
    b.kj_info(id,uid,that,function(t){
      that.setData(t)
      //倒计时
      if (t.bargain_info.end_time) {
        var time = t.bargain_info.end_time;
        b.Countdown(time, function (i) {
          that.setData(i)
        })
      }
    })
  },
  push: function (id, form_id){
    console.log(id)
    var that=this;
    console.log(form_id);
    console.log('----------------');
    a.get('Wxpush/BargainSuccessPush', {
      bargain_id: id,
      user_id: getApp().getCache("userinfo").uid,
      formid: form_id
    }, function (t) {
      console.log(t)
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },
  tankuang:function(){
    this.setData({
      popup:false
    })
  },

  /**
   * 回到名片页
   */
  toCard: function () {
    a.jump('/yb_mingpian/pages/card/index', 3);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.detail();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  /**
   * 跳转到砍价记录
   */
  record:function(){
    wx.navigateTo({
      url: '/yb_mingpian/pages/kanjia/record/index?id=' + this.data.user_info.id
    })
  },
  
  /**
   *立即购买
   * @param goods_id sku_id uid total
   * @return url
   */
  buyNow: function (t) {
    var i = this.data;
    if (i.overtime==1) {
      a.alert('该活动已过期')
      return false;
    }
    if (i.bargain_info.bargain_inventory < 1) {
      a.alert('库存不足')
      return false;
    }
    wx.navigateTo({
        url: "/yb_mingpian/pages/kanjia/order/create/index?bargain_id=" + i.bargain_info.id  + "&total=1&sku_id=" + "&uid=" + getApp().getCache("userinfo").uid + "&activity_order_type=1&current_price=" + i.user_info.current_price
      })
  },
  Forsubmit:function(e){
    this.setData({
      formId: e.detail.formId
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var that = this.data;

      return {
        title: getApp().getCache('userinfo').nickName + "邀请您帮忙砍价，最低可以砍到" + that.user_info.lowest_price+"元",
        path: '/yb_mingpian/pages/kanjia/share_info/index?id=' + that.user_info.id + '&uid=' + that.user_info.user_id + '&bargain_id=' + that.user_info.bargain_id + '&form_id=' + that.formId + "&card_id=" + app.globalData.card_id,
        success: function (res) {
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }
    
    
  },
  /**
   *点击按钮 弹出 选择规格、数量页面
   */
  selectPicker: function (t) {
    var that = this;
    if (that.data.bargain_info.bargain_inventory < 1) {
      a.alert('当前库存不足，请稍后再试');
      return;
    }
    if (that.data.goods_detail.goods_spec_format.length == 0) {
      wx.redirectTo({
        url: "/pages/order/create/index?bargain_id=" + that.data.bargain_info.id + "&goods_id=" + that.data.goods_detail.goods_id + "&total=1&sku_id=" + that.data.goods_detail.sku['0'].sku_id + "&uid=" + getApp().getCache("userinfo").uid + "&activity_order_type=1&current_price=" + that.data.user_info.current_price
      })
    }

    that.setData({
      active: "active",
      slider: "in",
      tempname: "select-picker"
    })
    var d = that.data.goods_detail.sku;
    //默认规格选中
    if (that.data.goods_detail.goods_spec_format.length != 0) {
      that.setData({
        optionid: d['0'].sku_id,
        "goods_detail.sku_pic": (d['0'].pic != null) ? d['0'].pic.img_cover_small : ''
      })

      var r = that.data.goods_detail.goods_spec_format,
        o = "",
        arr = [];
      r.forEach(function (t, k) {
        arr[k] = {
          id: t.spec_id,
          vid: t.value[0].spec_value_id,
          spec_name: t.value[0].spec_value_name
        }
        o += t.value[0].spec_value_name + "， "
      });
      that.setData({
        specsData: arr,
        specsTitle: o
      })
    } else {
      that.setData({
        "goods.sku_pic": (d['0'].pic != null) ? d['0'].pic.img_cover_small : ''
      })
    }
  },

  /**
   *选中规格后在data中储存相应的数量、价格、sku等信息
   */
  specsTap: function (t) {
    var e = this,
      o = "",
      i = "",
      a = t.target.dataset.idx,
      d = e.data.goods_detail.sku,
      r = e.data.specsData;
    r[a] = {
      id: t.target.dataset.id,
      vid: t.target.dataset.vid,
      spec_name: t.target.dataset.spec_name
    };
    r.forEach(function (t) {
      o += t.spec_name + "， ",
        i += t.id + ":" + t.vid + ";"
    });
    i = i.substring(0, i.length - 1);
    d.forEach(function (a) {
      console.log(a)
      a.attr_value_items == i && (e.setData({
        optionid: a.sku_id,
        "goods.sku_pic": (a.pic != null) ? a.pic.img_cover_small : ''
      })
      )
    }),
      e.setData({
        specsData: r,
        specsTitle: o
      })
  },
  /**
   *隐藏 选选数量、规格的 弹框
   */
  emptyActive: function () {
    this.setData({
      active: "",
      slider: "out",
      //showPicker: false,
    })
  }
})